<template>
    <div>
        <!-- //新增 -->
        <van-address-edit 
        :area-list="areaList" 
        show-delete 
        show-set-default 
        show-search-result
        :search-result="searchResult" 
        :area-columns-placeholder="['请选择', '请选择', '请选择']" 
        @save="onSave"
        @delete="onDelete" 
         v-model:addressDetail="addressDetail"
         
        
        />
      
    <div id="container">
    <input v-model="keyword" id="keyword" placeholder="请输入搜索位置" autocomplete="off" @keyup.enter="searchPlace" />
    <button @click="searchPlace">搜索</button>
    <div>
      <p>经度: {{ longitude }}</p>
      <p>纬度: {{ latitude }}</p>
      <p>{{ message }}</p>
        </div> 
    <div v-if="places.length" class="ban">
      <h3>搜索结果:</h3>
      <ul>
           <!-- @vue-ignore -->
        <li v-for="(place,i)  in places" :key="i" @click="selectPlace(place)">{{ place.name }}</li>
        
      </ul>
    </div>
  </div>
    </div>

      
</template>

<script lang="ts" setup>
import { ref ,onMounted } from 'vue';
import { showToast } from 'vant'
import { areaList } from '@vant/area-data';
import axios from 'axios'
import { useRouter } from 'vue-router';
import AMapLoader from '@amap/amap-jsapi-loader';
const address = ref({
    name: '',
    phone: '',
    city: '',
    desc: '',
    state: '',
})

const router=useRouter()
const searchResult = ref([]);
const addressDetail = ref(''); // 新增详细地址字段

const props = defineProps({
  message: String
})

interface Place{
  name:string
}
const keyword = ref('')
const longitude = ref<any>(null)
const latitude = ref<any>(null)
const places = ref<Place[]>([]) // 存储搜索结果
const emit = defineEmits(['update:longitude', 'update:latitude', 'update:address', 'childEvent', 'longitudeLi','latitudeLi','addressLi'])

let map: {
  Marker: any; on: (arg0: string, arg1: (e: any) => Promise<void>) => void; 
}
let marker: { setMap: (arg0: any) => void; } // 定义标记变量

// 初始化地图
const initMap = () => {
  AMapLoader.load({
    key: '10a926dc02f8811c879049c06b78031a',
    version: '1.4.15',
    plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
  }).then((AMap) => {
    map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 10,
      center: [116.397428, 39.90923]
    })
    emit('childEvent', 'Hello from Child!')

    // 点击地图事件
    map.on('click', async (e) => {
      longitude.value = e.lnglat.lng
      latitude.value = e.lnglat.lat
      emit('longitudeLi', longitude.value)
      emit('latitudeLi', latitude.value)

      const apiKey = '10a926dc02f8811c879049c06b78031a'
      const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude.value},${latitude.value}`
      try {
        const response = await fetch(url)
        const data = await response.json()

        if (data.status === '1') {
          const address = data.regeocode.formatted_address
          emit('addressLi', address)
        }
      } catch (error) {
        console.error('请求错误:', error)
      }
    })
  }).catch((error) => {
    console.error('加载 AMap 失败:', error)
  })
}

// 搜索地点
const searchPlace = async () => {
  const apiKey = '10a926dc02f8811c879049c06b78031a'
  const url = `https://restapi.amap.com/v3/place/text?keywords=${encodeURIComponent(keyword.value)}&key=${apiKey}&extensions=all`
  
  try {
    const response = await fetch(url)
    const data = await response.json()
    if (data.status === '1') {
      places.value = data.pois // 存储搜索结果
    } else {
      console.error('搜索失败:', data.info)
      places.value = []
      
    }
  } catch (error) {
    console.error('请求错误:', error)
  }
}

const editItem=ref()
const selectPlace = (place: { location: string; addressComponent: { city: any; }; name: any; }) => {
  longitude.value = place.location.split(',')[0]
  latitude.value = place.location.split(',')[1]

  // 提取城市信息并更新到 editItem 的 city 字段
  if (place.addressComponent && place.addressComponent.city) {
    editItem.value.city = place.addressComponent.city;
  } else {
    console.error('城市信息未找到');
  }

  // 更新详细地址字段
  editItem.value.desc = place.name; // 假设 place.name 包含详细地址信息

  // 在地图上添加标记
  if (marker) {
    marker.setMap(null);
  }
  marker = new map.Marker({
    position: [longitude.value, latitude.value],
    title: place.name
  });
  marker.setMap(map);

  console.log(`选择地点: ${place.name}, 经度: ${longitude.value}, 纬度: ${latitude.value}`);
}


// 在组件挂载后初始化地图
onMounted(initMap)

// 删除地址
const onDelete = () => showToast('delete');

// 保存地址
const onSave = (e:any) => {
    address.value = {
        name: e.name,
        phone: e.tel,
        city: e.province + e.city + e.county,
        desc: e.addressDetail,
        state: e.isDefault ? '1' : '0',  
    }
    
    axios.put('/api/address/add', address.value).then(res => {
        console.log(res)
    })
    router.back()
}


</script>

<style scoped>



#container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 376px;
  
}
#keyword {
  margin-top: 1%;
  height: 30px;
  position: absolute;
   z-index: 99;
  
}
.ban{
 z-index: 99999;
 position: relative;
 background: #ffff;
 top: 30px;
}


#map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

#map {
  width: 100%;
  height: 100%;
}
</style>